package controller

import (
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"mynetdisk/model"
	"mynetdisk/utils"
	"net/http"
	"os"
	"strings"
)

/**
 *@Author tudou
 *@Date 2019/8/24
 **/

func UploadOwnFile(c *gin.Context) {
	session := sessions.Default(c)
	username := session.Get("username").(string)
	userId := session.Get("user").(uint)
	finalPath := c.PostForm("finalPath")
	file, header, err := c.Request.FormFile("upload")
	defer file.Close()
	var f model.File
	if err != nil {
		utils.CheckErr(err, "upload the file failed")
		c.JSON(http.StatusBadRequest, gin.H{"error": "there is an unknown error"})
		return
	}
	if utils.DirExisted(finalPath, userId) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "please input the right path"})
		return
	}
	if strings.Contains(finalPath, ".") {
		c.JSON(http.StatusBadRequest, gin.H{"error": "please input the right path"})
		return
	}
	if utils.FileExisted(finalPath, header.Filename) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "the file name has existed"})
		return
	}
	md := utils.ParseFileToMd5(file)
	reFinalPath := StaticPath + utils.ParseUintToString(userId) + finalPath + header.Filename
	out, err := os.Create(reFinalPath)
	defer out.Close()
	if err != nil {
		utils.CheckErr(err, "create the file failed")
		c.JSON(http.StatusBadRequest, gin.H{"error": "there is an unknown error"})
		return
	}
	var reCap string = "0MB"
	if f.GetFileByMd5(md) {
		reCap = f.Cap
		rePath := StaticPath + utils.ParseUintToString(f.Uid) + f.Location + f.Name
		originFile, _ := os.Open(rePath)
		defer originFile.Close()
		_, err = io.Copy(out, originFile)
		if err != nil {
			utils.CheckErr(err, "copy the file failed")
			c.JSON(http.StatusOK, gin.H{"error": "there is an unknown error"})
			return
		}
	} else {
		_, err = io.Copy(out, file)
		content, err := ioutil.ReadAll(file)
		reCap = utils.ParseBytesToMB(content)
		if err != nil {
			utils.CheckErr(err, "read the file failed")
			c.JSON(http.StatusBadRequest, gin.H{"error": "there is an unknown error"})
			return
		}
	}
	var reFile = model.File{
		Uid:      userId,
		Cap:      reCap,
		Name:     header.Filename,
		Username: username,
		Location: finalPath,
		Md5:      md,
	}
	if !reFile.InsertFile() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "upload failed"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "upload successfully"})
}

func UploadOwnMutiFile(c *gin.Context) {
	session := sessions.Default(c)
	username := session.Get("username").(string)
	userId := session.Get("user").(uint)
	finalPath := c.PostForm("finalPath")
	err := c.Request.ParseMultipartForm(32 << 20)
	if utils.DirExisted(finalPath, userId) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "please input the right path"})
		return
	}
	if err != nil {
		utils.CheckErr(err, "parse mutipartForm failed")
		c.JSON(http.StatusOK, gin.H{"error": "parse mutipartForm failed"})
		return
	}
	formdata := c.Request.MultipartForm
	files := formdata.File["upload"]
	for i, _ := range files {
		file, err := files[i].Open()
		var ff model.File
		md:=utils.ParseFileToMd5(file)
		defer file.Close()
		if err != nil {
			utils.CheckErr(err, "open the file failed")
			c.JSON(http.StatusOK, gin.H{"error": "there is an unknown error"})
			return
		}
		if utils.FileExisted(finalPath, files[i].Filename) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "the file name has existed"})
			return
		}
		var reCap string="0MB"
		rePath := StaticPath + utils.ParseUintToString(userId) + finalPath + files[i].Filename
		out, err := os.Create(rePath)
		defer out.Close()
		if err != nil {
			utils.CheckErr(err, "create the file failed")
			c.JSON(http.StatusOK, gin.H{"error": "there is an unknown error"})
			return
		}
		if ff.GetFileByMd5(md) {
			reCap = ff.Cap
			rePath := StaticPath + utils.ParseUintToString(ff.Uid) + ff.Location + ff.Name
			originFile, _ := os.Open(rePath)
			defer originFile.Close()
			_, err = io.Copy(out, originFile)
			if err != nil {
				utils.CheckErr(err, "copy the file failed")
				c.JSON(http.StatusOK, gin.H{"error": "there is an unknown error"})
				return
			}
		} else {
			_, err = io.Copy(out, file)
			if err != nil {
				utils.CheckErr(err, "copy the file failed")
				c.JSON(http.StatusOK, gin.H{"error": "there is an unknown error"})
				return
			}
			content, err := ioutil.ReadAll(file)
			reCap = utils.ParseBytesToMB(content)
			if err != nil {
				utils.CheckErr(err, "read the file failed")
				c.JSON(http.StatusBadRequest, gin.H{"error": "there is an unknown error"})
				return
			}
		}
		var f = model.File{
			Uid:      userId,
			Cap:      reCap,
			Name:     files[i].Filename,
			Username: username,
			Location: finalPath,
			Md5:      md,
		}
		if !f.InsertFile() {
			c.JSON(http.StatusBadRequest, gin.H{"error": "upload failed"})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{"message": "upload successfully"})
}
